/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.afollestad.materialdialogs.utils;

import com.afollestad.materialdialogs.MaterialDialog;
import ohos.accessibility.ability.AccessibleAbility;
import ohos.accessibility.ability.SoftKeyBoardController;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Component;
import ohos.agp.components.element.Element;
import ohos.agp.window.dialog.IDialog;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

/**
 * @author Aidan Follestad (afollestad)
 */
public class DialogUtils {
    public static int adjustAlpha(int color, float factor) {
        RgbColor rgbColor = new RgbColor(color);
        int alpha = Math.round(rgbColor.getAlpha() * factor);
        int red = rgbColor.getRed();
        int green = rgbColor.getGreen();
        int blue = rgbColor.getBlue();
        return new RgbColor(red, green, blue, alpha).asArgbInt();
    }

    public static void setBackgroundCompat(Component view, Element d) {
        view.setBackground(d);
    }

    public static void showKeyboard(final IDialog di) {
        final MaterialDialog dialog = (MaterialDialog) di;
        if (dialog.getInputEditText() == null) {
            return;
        }
        new EventHandler(EventRunner.create()).postTask(new Runnable() {
            @Override
            public void run() {
                dialog.getInputEditText().requestFocus();
                SoftKeyBoardController ime = new SoftKeyBoardController(AccessibleAbility.SHOW_MODE_AUTO, null);
                ime.setShowMode(AccessibleAbility.SHOW_MODE_AUTO);
            }
        });
    }

    public static void hideKeyboard(final IDialog di) {
        final MaterialDialog dialog = (MaterialDialog) di;
        if (dialog.getInputEditText() == null) {
            return;
        }
        SoftKeyBoardController ime = new SoftKeyBoardController(AccessibleAbility.SHOW_MODE_AUTO, null);
        ime.setShowMode(AccessibleAbility.SHOW_MODE_HIDE);
    }

    public static <T> boolean isIn(T find, T[] ary) {
        if (ary == null || ary.length == 0) {
            return false;
        }
        for (T item : ary) {
            if (item.equals(find)) {
                return true;
            }
        }
        return false;
    }
}
